from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer

@csrf_exempt
def snippet_list(request):
    print('request in views.py========::',request)
    if request.method == 'GET':
        snippets = Snippet.objects.all()
        s = SnippetSerializer(snippets, many=True)
        return JsonResponse(s.data, safe=False)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        ds = SnippetSerializer(data=data)
        if ds.is_valid():
            ds.save()
            return JsonResponse(ds.data, status=201)
        return JsonResponse(ds.errors, status=400)

@csrf_exempt
def snippet_detail(request, pk):
    try:
        snippet = Snippet.objects.get(pk=pk)
    except Snippet.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        seri = SnippetSerializer(snippet)
        return JsonResponse(seri.data)

    elif request.method == 'PUT':
        data = JSONParser().parse(request)
        print('request in views.py========::', request.data)

        deseri = SnippetSerializer(snippet, data=data)
        if deseri.is_valid():
            deseri.save()
            return JsonResponse(deseri.data)
        return JsonResponse(deseri.errors, status=404)

    elif request.method == 'DELETE':
        snippet.delete()
        return HttpResponse(status=404)